package com.testDemo.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * @author: zouren
 * @date: 2022/3/10
 * @description:
 */
public class FindJar {
    // jar包父目录
    public static final String path = "D:\\zouren\\workspace\\old-picchealth\\onecard\\EAPDomain\\WEB-INF\\lib";
    // 关键字
    public static final String keywords = "CheckThread";
    static final Pattern p = Pattern.compile(".+\\.jar$");
    public static void main(String[] args) {
        searchByJar(path,keywords);
    }
    public static void searchByJar(String jarHome,String searchTest){
        File file = new File(jarHome);
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (p.matcher(pathname.getPath()).matches()) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        search(files,searchTest);
    }
    private static void search(File[] files,String searchTest) {
        try {
            for (File f : files) {
                if (f.isDirectory()) {
                    search(f.listFiles(),searchTest);
                } else {
                    ZipFile jar = new ZipFile(f);
                    Enumeration enumration = jar.entries();
                    while (enumration.hasMoreElements()) {
                        ZipEntry zipEntry = (ZipEntry) enumration.nextElement();

                        InputStreamReader isr = new InputStreamReader(jar.getInputStream(zipEntry));
                        BufferedReader br = new BufferedReader(isr);
                        String line = br.readLine();
                        int line_num = 1;
                        while (null != line) {
//                             System.out.println(line);
                            if (line.contains(searchTest)) {
                                System.out.println(f.getPath() + "," + zipEntry.getName() + "," + "line number = " + line_num);
                            }
                            line = br.readLine();
                            line_num++;
                        }
                    }
                }
            }
        } catch (ZipException z_e) {
            z_e.printStackTrace();
        } catch (IOException io_e) {
            io_e.printStackTrace();
        }
    }
}
